# -*- coding: utf-8 -*-
from utils.config import *
from utils.utils import *
import pandas as pd
import utils.MyTT as Mytt
# import logging
from utils.log import Loggers
from utils.pushService import PushService

logger = Loggers('MovingAverage')
# logger.clear()

pushSer = PushService('影线反转策略')

# 识别影线
def identify_shadows(df, min_body_ratio=0.3, min_shadow_ratio=2.0):
    """
    识别长影线K线
    参数:
        min_body_ratio: 实体部分占整根K线的最小比例(默认30%)
        min_shadow_ratio: 影线与实体的最小比例(默认2倍)
    返回:
        带有信号标记的DataFrame
    """
    df = df.copy()
    
    # 计算K线各部分长度
    df['body'] = abs(df['close'] - df['open'])
    df['total_range'] = df['high'] - df['low']
    df['upper_shadow'] = df['high'] - df[['open','close']].max(axis=1)
    df['lower_shadow'] = df[['open','close']].min(axis=1) - df['low']
    
    # 识别长上影线条件
    upper_cond = (
        (df['body'] / df['total_range'] < min_body_ratio) & 
        (df['upper_shadow'] / df['body'] > min_shadow_ratio) & 
        (df['close'] > df['open'])
    )
    
    # 识别长下影线条件
    lower_cond = (
        (df['body'] / df['total_range'] < min_body_ratio) & 
        (df['lower_shadow'] / df['body'] > min_shadow_ratio) & 
        (df['close'] < df['open'])
    )
    
    df['upper_shadow_signal'] = upper_cond.astype(int)
    df['lower_shadow_signal'] = lower_cond.astype(int)
    
    return df


# 循环处理
for instId in config_movingAverage_instId:
    # 读取300条最新的数据
    df = loadCsvData(instId,'4h',300)

    # 20日成交量
    df['volume_ma20'] = Mytt.MA(df['volume'],20)
    # 20日均线
    df['ma20'] =  Mytt.MA(df['close'],20)

    df.loc[(df['close']> df['ma20']),'trend'] = 1 # 上升趋势
    df.loc[(df['close']< df['ma20']),'trend'] = -1 # 上升趋势
    # 标记影线
    df = identify_shadows(df)
    df['signal'] = 0
    df.loc[ (df['volume'] > df['volume_ma20']) &  df['upper_shadow_signal']==1,'signal'] = 1 # 做多
    df.loc[ (df['volume'] > df['volume_ma20']) &  df['lower_shadow_signal']==1,'signal'] = -1 # 做空

    # 快速计算近期胜率
    shenglv5,shenglv10 = getShenglv(df)

    # 取出所有满足条件的信号数据
    df_signal = df[df['signal']!=0]
    df_signal = df_signal[['open','close','signal','diezhang_5','diezhang_10']]
    # 拿到最后出现信号的数据
    # after_signal = df_signal.iloc[-1]
    # print(df_signal.tail(20))
    print(f"{instId} 信号数量：{len(df_signal)} 5日胜率：{shenglv5}% 10日胜率：{shenglv10}%")

    # exit()